package com.veepeak.server.api.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.veepeak.server.common.JSONResult;
import com.veepeak.server.domain.DtcCommand;
import com.veepeak.server.domain.Obd;
import com.veepeak.server.service.DtcCommandService;
import com.veepeak.server.service.ObdService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "/upload")
@Api(description = "文件上传")
public class FileUploadApi {
    private final static Logger LOG = LoggerFactory.getLogger(FileUploadApi.class);
    @Autowired
    private ObdService obdService;
    @Autowired
    private DtcCommandService dtcCommandService;

    @RequestMapping(value = "/new-obd")
    @ResponseBody
    public JSONObject uploadObd(@RequestParam("uploadfile") MultipartFile file) {
        if (file.isEmpty()) {
            return JSONResult.toFailureJson("上传的文件为空");
        }
        int uploadCounts = 0;
        try {
            File destFile = File.createTempFile(UUID.randomUUID().toString(), "");
            file.transferTo(destFile);
            List<Obd> uploadList = analysis(destFile);
            uploadCounts = obdService.upload(uploadList);
            return JSONResult.toSuccessJson("数据上传成功,共上传"+uploadCounts+"条设备信息!");
        } catch (Exception e) {
            return JSONResult.toFailureJson("数据上传失败:"+e.getMessage());
        }


    }

    public List<Obd> analysis(File file) throws Exception{
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook(file);
        XSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
        String[] titleForm = {"Serials Number","Product Model","Produce Date","Order Sn","Remark"};

        //check format
        XSSFRow titleRow = hssfSheet.getRow(0);
        boolean checked =
                (StringUtils.compare(titleRow.getCell(0).getStringCellValue(),titleForm[0]) +
                        StringUtils.compare(titleRow.getCell(1).getStringCellValue(),titleForm[1]) +
                        StringUtils.compare(titleRow.getCell(2).getStringCellValue(),titleForm[2]) +
                        StringUtils.compare(titleRow.getCell(3).getStringCellValue(),titleForm[3]) +
                        StringUtils.compare(titleRow.getCell(4).getStringCellValue(),titleForm[4]))  == 0  ;

        if ( !checked ) throw  new RuntimeException("upload template validation error !");

        List<Obd> uploadObdList = Lists.newArrayList();
        for (int i=1; i<=hssfSheet.getLastRowNum(); i++){
            XSSFRow row = hssfSheet.getRow(i);
            String serialNo = row.getCell(0).getStringCellValue();
            String productModel = row.getCell(1).getStringCellValue();
            String produceDate = row.getCell(2).getStringCellValue();
            String orderSn = row.getCell(3).getStringCellValue();
            String remark = row.getCell(4).getStringCellValue();
            uploadObdList.add(new Obd(serialNo,productModel,produceDate,orderSn,remark));
        }

        return uploadObdList;
    }

    @RequestMapping(value = "/new-dtc")
    @ResponseBody
    public JSONObject uploadDtc(@RequestParam("uploadfile") MultipartFile file) {
        if (file.isEmpty()) {
            return JSONResult.toFailureJson("上传的文件为空");
        }

        try {
            File destFile = File.createTempFile(UUID.randomUUID().toString(), "");
            file.transferTo(destFile);
            List<DtcCommand> uploadList = analysisDtcFile(destFile);
            Map<String,String> uploadResult = dtcCommandService.upload(uploadList);
            return JSONResult.toSuccessJson(uploadResult,"");
        } catch (Exception e) {
            return JSONResult.toFailureJson("数据上传失败:"+e.getMessage());
        }
    }

    private List<DtcCommand> analysisDtcFile(File file) throws Exception {
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook(file);
        XSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
        String[] titleForm = {"Pid","Description"};

        //check format
        XSSFRow titleRow = hssfSheet.getRow(0);
        boolean checked =
                (StringUtils.compare(titleRow.getCell(0).getStringCellValue(),titleForm[0]) +
                        StringUtils.compare(titleRow.getCell(1).getStringCellValue(),titleForm[1]))  == 0  ;

        if ( !checked ) throw  new RuntimeException("upload template validation error !");

        List<DtcCommand> commandList = Lists.newArrayList();

        for (int i=1; i<=hssfSheet.getLastRowNum(); i++){
            XSSFRow row = hssfSheet.getRow(i);
            String pid = row.getCell(0).getStringCellValue();
            String description = row.getCell(1).getStringCellValue();
            commandList.add(new DtcCommand(pid,description,""));
        }

        return commandList;
    }
}
